package gwin.com.numbers;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by YuZui on 2020/6/18 0018.
 */
public class Grid {
    Game g;
    boolean isUnknown;
    int fillNumber;
    List<Grid> sameList = new ArrayList<>();
    int number;
    int x;
    int y;

    public Grid(Game g, int i, int j) {
        isUnknown = false;
        this.g = g;
        x = i;
        y = j;
    }

    public void fillNumber(int number) {
        fillNumber = number;
        testError();
        g.testGameOver();
    }

    private void testError() {
        //横排
        for (int i = 0; i < 9; i++) {
            if (i == x) continue;
            isSameWith(g.grids[i][y]);
        }
        //竖排
        for (int i = 0; i < 9; i++) {
            if (i == y) continue;
            isSameWith(g.grids[x][i]);
        }
        //所处中型格子
        int boxX = x / 3;
        int boxY = y / 3;
        for (int i = boxX * 3; i < boxX * 3 + 3; i++) {
            for (int j = boxY * 3; j < boxY * 3 + 3; j++) {
                if (i == x && j == y) continue;
                isSameWith(g.grids[i][j]);
            }
        }
    }

    private void isSameWith(Grid grid) {
        if (grid.fillNumber == 0) return;
        if ((grid.isUnknown ? grid.fillNumber : grid.number) == fillNumber) {
            sameList.add(grid);
            grid.sameList.add(this);
        }
    }

    public void eraseNumber() {
        if (!isUnknown) return;
        if (fillNumber == 0) return;
        fillNumber = 0;
        int count = sameList.size();
        for (int i = 0; i < count; i++) {
            sameList.get(i).sameList.remove(this);
        }
        sameList.clear();
    }


    public void reset(Game g) {
        this.g = g;
        isUnknown = false;
        sameList.clear();
    }

    public boolean isSelected() {
        return g.curX == x && g.curY == y;
    }

    public void setAsUnknown() {
        fillNumber = 0;
        isUnknown = true;
    }
}
